﻿using QPlcPlayer.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QPlcPlayer.Services
{
    public class AgvCarService:QMainService
    {
        public AgvCar GetAgvCarById(string id)
        {
            if (string.IsNullOrWhiteSpace(id)) return default;
            var db=CreateDbContext();
            var info=db.Set<AgvCar>().FirstOrDefault(x=>x.ID==id);
            return info;
        }

        public AgvCar GetAgvCarByNumber(int carNumber)
        {
			 var db = CreateDbContext();
			var info = db.Set<AgvCar>().FirstOrDefault(x => x.CarNumber == carNumber.ToString());
			return info;
		}
		public AgvCar GetAgvCarByNumber(string carNumber)
		{
			var db = CreateDbContext();
			var info = db.Set<AgvCar>().FirstOrDefault(x => x.CarNumber == carNumber);
			return info;
		}
		public List<AgvCar> GetAgvCarList()
        {
             var db=CreateDbContext();
            var res=db.Set<AgvCar>().OrderBy(x=>x.CarNumber).ToList();
            return res;
        }

        public bool AddOrUpdateAgvCar(AgvCar info)
        {

            if(info==null) return false;
             var db = CreateDbContext();
            if (string.IsNullOrWhiteSpace(info.ID))
            {

                info.ID=Guid.NewGuid().ToString();
                db.Set<AgvCar>().Add(info);

            }
            else
            {
                var exits = db.Set<AgvCar>().Find(info.ID);
                if (exits != null)
                {
                    exits.CarNumber = info.CarNumber;
                    exits.Description=info.Description;
                }

            }

            db.SaveChanges();
            return true;
        }

        public bool UpdateAgvCarPLC(AgvCar info)
        {
			if (info == null) return false;
			var db = CreateDbContext();
			var exits = db.Set<AgvCar>().FirstOrDefault(x=>x.CarNumber==info.CarNumber);
			if (exits != null)
            {
                exits.PlcType = info.PlcType;
                exits.IP = info.IP;
            }
			db.SaveChanges();
			return true;
		}
        public bool DeleteAgvCar(string id)
        {
             var db=CreateDbContext();
            var info=db.Set<AgvCar>().FirstOrDefault(y=>y.ID==id);
            if (info != null)
            {
                db.Set<AgvCar>().Remove(info);
               
            }
           
            db.SaveChanges();
            return true;
        }

        public bool UpdateCarInfo(string carNumber,CarStatus carStatus,string electricity)
        {
            var db = CreateDbContext();
            var info = db.Set<AgvCar>().FirstOrDefault(x => x.CarNumber == carNumber);
            if (info != null)
            {
                info.CarStatus = carStatus;
                info.Electricity = electricity;
            }
            db.SaveChanges();
            return true;    
        }


    }
}
